package com.kongwg.java;

import org.junit.Test;

import java.io.*;

/**
 * @author kongwg
 * @create 2020-12-19 14:55
 */
public class ObjectInputOutputTest {

    /**
     * 序列化：将java对象或者基本数据类型转换为磁盘中的文件
     * ObjectOutputStream()
     */
    @Test
    public void ObjectOutputStreamTest() {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));

            oos.writeObject(new String("java语言的学习，我很快乐"));

            oos.writeObject(new Person("瑞秋",20));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 反序列化：将硬盘中的文件读取到java对象中
     * ObjectInputStream()
     */

    @Test
    public void ObjectIntputStreamTest() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object o = ois.readObject();

            String s = (String) o;
            System.out.println(s);

            Person p = (Person) ois.readObject();
            System.out.println(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {

                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

